<template>
  <div class="box-main">
    <div class="topHeaderCard">
      <a-card>
        <a-tabs v-model:activeKey="activeKey" :bordered="false" size="small" @change="tabsChange">
          <a-tab-pane
            v-for="item in diseaseLite"
            :key="item.id + ''"
            :tab="item.groupName"
          ></a-tab-pane>
        </a-tabs>
      </a-card>
    </div>
    <div class="bax-main-content">
      <div class="box-content">
        <a-card :bordered="false">
          <span class="title-name">基本情况</span>

          <a-spin :spinning="isBasicSpinning" tip="加载中...">
            <div class="basic-info">
              <div class="year-patient">
                <div class="icon-img">
                  <img src="@/assets/data-statistics/1.png" alt="" />
                </div>
                <div class="info-content">
                  <div class="data-col-title">本年已治疗患者数</div>
                  <div class="data-value">
                    <CountTo
                      :startVal="0"
                      :endVal="basicPatData ? basicPatData.treatNum : 0"
                      :duration="1000"
                    >
                    </CountTo>
                  </div>
                  <div class="data-yoy">
                    同比上年
                    <a-tag
                      :bordered="false"
                      :color="
                        basicPatData &&
                        basicPatData.treatNumRatio &&
                        parseFloat(basicPatData.treatNumRatio) < 0
                          ? 'error'
                          : 'success'
                      "
                    >
                      {{ Math.abs(basicPatData ? basicPatData.treatNumRatio : 0) }}%
                      <img
                        v-if="
                          basicPatData &&
                          basicPatData.treatNumRatio &&
                          parseFloat(basicPatData.treatNumRatio) < 0
                        "
                        src="@/assets/data-statistics/down.png"
                        alt=""
                      />
                      <img v-else src="@/assets/data-statistics/up.png" alt="" />
                    </a-tag>
                  </div>
                </div>
              </div>
              <div class="other-patient">
                <div class="first-patient">
                  <div>
                    <div class="data-col-title">首次治疗患者数</div>
                    <div class="data-value">
                      <CountTo
                        :startVal="0"
                        :endVal="basicPatData ? basicPatData.firstNum : 0"
                        :duration="1000"
                      >
                      </CountTo>
                    </div>
                    <div class="data-yoy">
                      同比上年
                      <a-tag
                        :bordered="false"
                        :color="
                          basicPatData &&
                          basicPatData.firstNumRatio &&
                          parseFloat(basicPatData.firstNumRatio) < 0
                            ? 'error'
                            : 'success'
                        "
                      >
                        {{ Math.abs(basicPatData ? basicPatData.firstNumRatio : 0) }}%
                        <img
                          v-if="
                            basicPatData &&
                            basicPatData.firstNumRatio &&
                            parseFloat(basicPatData.firstNumRatio) < 0
                          "
                          src="@/assets/data-statistics/down.png"
                          alt=""
                        />
                        <img v-else src="@/assets/data-statistics/up.png" alt="" />
                      </a-tag>
                    </div>
                  </div>
                </div>
                <div class="first-treatment-num">
                  <div>
                    <div class="data-col-title">首次治疗根除率</div>
                    <div class="data-value">
                      <CountTo
                        :startVal="0"
                        :endVal="basicPatData ? basicPatData.firstRate : 0"
                        :suffix="'%'"
                        :duration="1000"
                      ></CountTo>
                    </div>
                    <div class="data-yoy">
                      同比上年
                      <a-tag
                        :bordered="false"
                        :color="
                          basicPatData &&
                          basicPatData.firstRateRatio &&
                          parseFloat(basicPatData.firstRateRatio) < 0
                            ? 'error'
                            : 'success'
                        "
                      >
                        {{ Math.abs(basicPatData ? basicPatData.firstRateRatio : 0) }}%
                        <img
                          v-if="
                            basicPatData &&
                            basicPatData.firstRateRatio &&
                            parseFloat(basicPatData.firstRateRatio) < 0
                          "
                          src="@/assets/data-statistics/down.png"
                          alt=""
                        />
                        <img v-else src="@/assets/data-statistics/up.png" alt="" />
                      </a-tag>
                    </div>
                  </div>
                </div>
                <div class="first-treatment-percent">
                  <div>
                    <div class="data-col-title">二次治疗患者数</div>
                    <div class="data-value">
                      <CountTo
                        :startVal="0"
                        :endVal="basicPatData ? basicPatData.secondNum : 0"
                        :duration="1000"
                      >
                      </CountTo>
                    </div>
                    <div class="data-yoy">
                      同比上年
                      <a-tag
                        :bordered="false"
                        :color="
                          basicPatData &&
                          basicPatData.secondNumRatio &&
                          parseFloat(basicPatData.secondNumRatio) < 0
                            ? 'error'
                            : 'success'
                        "
                      >
                        {{ Math.abs(basicPatData ? basicPatData.secondNumRatio : 0) }}%
                        <img
                          v-if="
                            basicPatData &&
                            basicPatData.secondNumRatio &&
                            parseFloat(basicPatData.secondNumRatio) < 0
                          "
                          src="@/assets/data-statistics/down.png"
                          alt=""
                        />
                        <img v-else src="@/assets/data-statistics/up.png" alt="" />
                      </a-tag>
                    </div>
                  </div>
                </div>
                <div class="sec-treatment-num">
                  <div>
                    <div class="data-col-title">二次治疗根除率</div>
                    <div class="data-value">
                      <CountTo
                        :startVal="0"
                        :endVal="basicPatData ? basicPatData.secondRate : 0"
                        :suffix="'%'"
                        :duration="1000"
                      ></CountTo>
                    </div>
                    <div class="data-yoy">
                      同比上年
                      <a-tag
                        :bordered="false"
                        :color="
                          basicPatData &&
                          basicPatData.secondRateRatio &&
                          parseFloat(basicPatData.secondRateRatio) < 0
                            ? 'error'
                            : 'success'
                        "
                      >
                        {{ Math.abs(basicPatData ? basicPatData.secondRateRatio : 0) }}%
                        <img
                          v-if="
                            basicPatData &&
                            basicPatData.secondRateRatio &&
                            parseFloat(basicPatData.secondRateRatio) < 0
                          "
                          src="@/assets/data-statistics/down.png"
                          alt=""
                        />
                        <img v-else src="@/assets/data-statistics/up.png" alt="" />
                      </a-tag>
                    </div>
                  </div>
                </div>
                <div class="sec-treatment-percent">
                  <div>
                    <div class="data-col-title">确诊患者数</div>
                    <div class="data-value">
                      <CountTo
                        :startVal="0"
                        :endVal="basicPatData ? basicPatData.confirmNum : 0"
                        :duration="1000"
                      >
                      </CountTo>
                    </div>
                    <div class="data-yoy">
                      同比上年
                      <a-tag
                        :bordered="false"
                        :color="
                          basicPatData &&
                          basicPatData.confirmNumRatio &&
                          parseFloat(basicPatData.confirmNumRatio) < 0
                            ? 'error'
                            : 'success'
                        "
                      >
                        {{ Math.abs(basicPatData ? basicPatData.confirmNumRatio : 0) }}%
                        <img
                          v-if="
                            basicPatData &&
                            basicPatData.confirmNumRatio &&
                            parseFloat(basicPatData.confirmNumRatio) < 0
                          "
                          src="@/assets/data-statistics/down.png"
                          alt=""
                        />
                        <img v-else src="@/assets/data-statistics/up.png" alt="" />
                      </a-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </a-spin>
          <div class="content-title">确诊治疗情况</div>
          <div class="treatment-time-pick">
            <a-radio-group
              v-model:value="treatmentTimeType"
              size="small"
              button-style="solid"
              style="margin-right: 16px"
              @change="handleTreatmentTimeTypeChange"
            >
              <a-radio-button value="month">本月</a-radio-button>
              <a-radio-button value="year">本年</a-radio-button>
            </a-radio-group>
            <a-range-picker
              size="small"
              v-model:value="treatmentTime"
              style="width: 235px"
              @change="treatmentTimeChange"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            ></a-range-picker>
          </div>
          <a-spin :spinning="isTreatmentSpinning" tip="加载中...">
            <div v-if="treatmentAxias.length" id="treatment-situation"></div>
            <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" style="height: 300px" />
          </a-spin>
        </a-card>
      </div>
      <div class="box-content">
        <a-card :bordered="false">
          <span class="title-name">检验检查情况</span>
          <a-row :gutter="20" style="height: 260px">
            <a-col :span="10">
              <div class="content-title">诊断检测</div>
              <a-spin :spinning="isDiagnosticSpinning" tip="加载中...">
                <div v-if="diagnosticDataRatio.length" id="diagnostic-testing"></div>
                <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" style="height: 180px" />
              </a-spin>
            </a-col>
            <a-col :span="7">
              <div class="content-title">检出情况</div>
              <a-table
                class="ant-table-striped"
                size="small"
                :columns="columnsDetection"
                :data-source="dataDetection"
                :pagination="false"
                :loading="isDetectionSpinning"
                :scroll="{ y: 175 }"
                :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
              >
                <template #bodyCell="{ column, text }">
                  <template v-if="column.dataIndex == 'ratio'"> {{ text }}% </template>
                </template>
              </a-table>
            </a-col>
            <a-col :span="7">
              <div class="content-title">耐药检测</div>
              <a-table
                class="ant-table-striped"
                size="small"
                :columns="columnsResistent"
                :data-source="dataResistent"
                :loading="isResistentSpinning"
                :pagination="false"
                :scroll="{ y: 175 }"
                :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
              >
                <template #bodyCell="{ column, text }">
                  <template v-if="column.dataIndex == 'reportNumRatio'"> {{ text }}% </template>
                </template>
              </a-table>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div class="box-content">
        <a-card :bordered="false">
          <span class="title-name">用药情况</span>
          <a-row :gutter="20" style="height: 340px">
            <a-col :span="8">
              <div class="content-title">抗生素用药情况</div>
              <a-table
                class="ant-table-striped"
                size="small"
                :columns="columnsAntibiotic"
                :data-source="dataAntibiotic"
                :loading="isAntibioticSpinning"
                :pagination="false"
                :scroll="{ y: 235 }"
                :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
              >
                <template #bodyCell="{ column, text }">
                  <template v-if="column.dataIndex == 'useNumRatio'"> {{ text }}% </template>
                </template>
              </a-table>
            </a-col>
            <a-col :span="8">
              <div class="content-title">用药方案</div>
              <a-spin :spinning="isDrugPlanSpinning" tip="加载中...">
                <div v-if="drugPlanData.length" id="therapeutic-regimen"></div>
                <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" style="height: 180px" />
              </a-spin>
              <div class="therapeutic-tips">
                <a-row :gutter="10">
                  <a-col :span="6" v-for="(item, index) in therapeuticTipsData" :key="index">{{
                    item
                  }}</a-col>
                </a-row>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="content-title">耐药情况</div>
              <div class="drug-area-pick">
                <a-radio-group
                  v-model:value="areaValue"
                  size="small"
                  button-style="solid"
                  @change="handleAreaChange"
                >
                  <a-radio-button value="萧山">萧山</a-radio-button>
                  <a-radio-button value="杭州">杭州</a-radio-button>
                  <a-radio-button value="浙江">浙江</a-radio-button>
                </a-radio-group>
              </div>
              <a-spin :spinning="isDrugRenSpinning" tip="加载中..." style="width: 100%">
                <div v-if="drupAxisData.length" id="drug-resistance-situation"></div>
                <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" style="height: 240px" />
              </a-spin>
            </a-col>
          </a-row>
        </a-card>
      </div>
      <div class="box-content">
        <a-card :bordered="false">
          <span class="title-name">业务数据</span>
          <a-row :gutter="20" style="height: 350px">
            <a-col :span="12">
              <div class="content-title">管理业务</div>
              <div class="business-time-pick">
                <a-range-picker
                  size="small"
                  v-model:value="businessTime"
                  style="width: 180px"
                  picker="month"
                  @change="businessTimeChange"
                  :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                ></a-range-picker>
              </div>
              <a-spin :spinning="isManageSpinning" tip="加载中...">
                <div v-if="manageAxisData.length" id="manage-business"></div>
                <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" style="height: 230px" />
              </a-spin>
            </a-col>
            <a-col :span="12">
              <div class="content-title">AI挖掘潜在患者数量</div>
              <div v-if="aiMiningData.length" id="potential-number-patients"></div>
              <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" style="height: 240px" />
            </a-col>
          </a-row>
        </a-card>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts'
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import CountTo from '@/components/CountTo/vue-countTo.vue'
import dayjs, { Dayjs } from 'dayjs'
import { Empty } from 'ant-design-vue'
import {
  basicPat,
  diagnosed,
  diagnostic,
  resistent,
  antibiotic,
  drugPlan,
  detection,
  resistantDrug,
  manage,
  aiData,
  diseaseGroupList
} from '@/api/data-statistics/index.ts'

const mainChart = echarts
const activeKey = ref()
let diseaseName = ''
const areaValue = ref('萧山')

const isBasicSpinning = ref(true)
const isTreatmentSpinning = ref(true)
const isDiagnosticSpinning = ref(true)
const isResistentSpinning = ref(true)
const isAntibioticSpinning = ref(true)
const isDrugPlanSpinning = ref(true)
const isDetectionSpinning = ref(true)
const isDrugRenSpinning = ref(true)
const isManageSpinning = ref(true)

const treatmentTimeType = ref('month')

const treatmentTime = ref([dayjs(new Date()).startOf('months'), dayjs(new Date())])
const basicPatData = ref({})

const businessTime = ref([dayjs(new Date()).subtract(1, 'months'), dayjs(new Date())])

let chartsList = []

const therapeuticTipsData = [
  'B：铋剂',
  'PPI：质子泵抑制剂',
  'A：阿莫西林',
  'C：克拉霉素',
  'T：四环素',
  'M：甲硝唑',
  'L：左氧氟沙星',
  'F：呋喃唑酮'
]

// 确诊治疗
const treatmentAxias = ref([])
const treatmentConfirmData = ref([]) // 确诊
const treatmentTreatNum = ref([]) // 治疗人数

// 用药方案
const drugPlanData = ref([])

// 诊断检测
const diagnosticData = ref([])
const nonInvasiveRatio = ref()
const diagnosticDataRatio = ref([])

// 检出情况
const columnsDetection = [
  {
    title: '检出项目名称',
    dataIndex: 'name',
    width: 150
  },
  {
    title: '检出人次',
    dataIndex: 'num',
    width: 100
  },
  {
    title: '检出率',
    dataIndex: 'ratio'
  }
]
let dataDetection: any = []

// 耐药检测
const columnsResistent = [
  {
    title: '检测名称',
    dataIndex: 'testName'
  },
  {
    title: '平均报告周期',
    dataIndex: 'avgReportDay'
  },
  {
    title: '使用人次',
    dataIndex: 'reportNum'
  },
  {
    title: '占比',
    dataIndex: 'reportNumRatio',
    width: 80
  }
]
let dataResistent: any = []

// 抗生素用药
const columnsAntibiotic = [
  {
    title: '抗生素名称',
    dataIndex: 'drugName',
    width: 150
  },
  {
    title: '使用人次',
    dataIndex: 'useNum',
    width: 100
  },
  {
    title: '占比',
    dataIndex: 'useNumRatio',
    width: 50
  }
]
let dataAntibiotic: any = []

// 耐药情况
const drupAxisData = ref([])
const drupSeriesData = ref([])

// 管理业务
const manageAxisData = ref([])
// 智能提醒
const autoAxisData = ref([])
// 健康宣教
const healthAxisData = ref([])
// ai随访
const aiAxisData = ref([])
// 人工随访
const manualAxisData = ref([])
// 不良反应
const adverseAxisData = ref([])

// ai挖掘
const aiMiningData = ref([])

onMounted(() => {
  nextTick(async () => {
    diseaseLite.value = []
    activeKey.value = '-1'
    diseaseName = ''

    await diseaseGroupList().then((res) => {
      diseaseLite.value = res.data
      if (res.data && res.data.length) {
        activeKey.value = res.data[0].id + ''
        diseaseName = res.data[0].groupName

        init()
      } else {
        isBasicSpinning.value = false
        isTreatmentSpinning.value = false
        isDiagnosticSpinning.value = false
        isResistentSpinning.value = false
        isAntibioticSpinning.value = false
        isDrugPlanSpinning.value = false
        isDetectionSpinning.value = false
        isDrugRenSpinning.value = false
        isManageSpinning.value = false
      }
    })

    window.addEventListener('resize', () => {
      if (chartsList.length) {
        chartsList.forEach((chart) => {
          chart.resize()
        })
      }
    })
  })
})

onUnmounted(() => {
  mainChart.dispose
  window.addEventListener('resize', () => {})
  chartsList = []
})

const diseaseLite = ref([])

const init = async () => {
  dataDetection = []
  basicPatData.value = {}
  dataResistent = []
  dataAntibiotic = []

  // 基本情况
  basicPat({
    diseaseGroup: diseaseName
  }).then((res) => {
    isBasicSpinning.value = false
    basicPatData.value = res.data
  })

  // 耐药检测
  resistent({
    diseaseGroup: diseaseName
  }).then((res) => {
    isResistentSpinning.value = false
    dataResistent = res.data || []
  })

  // 抗生素用药
  antibiotic({ diseaseGroup: diseaseName }).then((res) => {
    isAntibioticSpinning.value = false
    dataAntibiotic = res.data || []
  })

  // 检出情况
  detection({ diseaseGroup: diseaseName }).then((res) => {
    isDetectionSpinning.value = false
    if (res.data) {
      dataDetection.push(
        {
          name: '胃镜HP检测',
          num: res.data.descriptionGcyNum,
          ratio: res.data.descriptionGcyNumRatio
        },
        {
          name: 'C14呼气试验',
          num: res.data.descriptionC14Num,
          ratio: res.data.descriptionC14NumRatio
        },
        {
          name: 'C13呼气试验',
          num: res.data.descriptionC13Num,
          ratio: res.data.descriptionC13NumRatio
        },
        {
          name: '粪便抗原检测',
          num: res.data.descriptionHpsaNum,
          ratio: res.data.descriptionHpsaNumRatio
        }
      )

      dataDetection = [...dataDetection]
    }
  })

  initChart()
}

// 确诊治疗情况时间类型切换
const handleTreatmentTimeTypeChange = (value) => {
  treatmentTimeType.value = value.target.value

  switch (value.target.value) {
    case 'month':
      treatmentTime.value = [dayjs(new Date()).startOf('months'), dayjs(new Date())]
      break
    case 'year':
      treatmentTime.value = [dayjs(new Date().getFullYear() + '-01-01'), dayjs(new Date())]
      break
  }

  initTreatment()
}

// 确诊治疗情况时间选择
const treatmentTimeChange = (date, dateString: string) => {
  if (dateString[0]) {
    treatmentTime.value = [dayjs(dateString[0]), dayjs(dateString[1])]
  } else {
    treatmentTime.value = []
  }

  initTreatment()
}

// 确诊治疗
const initTreatment = async () => {
  treatmentAxias.value = []
  treatmentConfirmData.value = []
  treatmentTreatNum.value = []
  // 确诊治疗情况
  await diagnosed({
    diseaseGroup: diseaseName,
    startDate: treatmentTime.value.length ? dayjs(treatmentTime.value[0]).format('YYYY-MM-DD') : '',
    endDate: treatmentTime.value.length ? dayjs(treatmentTime.value[1]).format('YYYY-MM-DD') : ''
  }).then((res) => {
    isTreatmentSpinning.value = false
    if (res.data && res.data.length) {
      res.data.forEach((element) => {
        treatmentAxias.value.push(element.countDate)
        treatmentConfirmData.value.push(element.confirmNum)
        treatmentTreatNum.value.push(element.treatNum)
      })
    }

    if (treatmentAxias.value.length) {
      nextTick(() => {
        initTreatmentChart()
      })
    }
  })
}

// 加载图表
const initTreatmentChart = () => {
  const dom = document.getElementById('treatment-situation')
  let myChart = mainChart.getInstanceByDom(dom)
  if (!myChart) {
    myChart = mainChart.init(dom)
    chartsList.push(myChart)
  }
  myChart.setOption({
    title: {
      show: treatmentAxias.value.length ? false : true,
      text: '暂无数据',
      left: 'center',
      top: 'middle',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    grid: {
      top: 30,
      left: 50,
      bottom: 100,
      right: 35
    },
    color: ['rgba(109, 210, 48, 1)', 'rgba(56, 125, 255, 1)'],
    toolbox: {},
    tooltip: {
      trigger: 'axis'
      // axisPointer: {
      //   type: 'cross',
      //   animation: false,
      //   label: {
      //     backgroundColor: 'rgba(0,0,0,0.7)'
      //   }
      // },
      // backgroundColor: 'rgba(0,0,0,0.7)',
      // textStyle: {
      //   color: '#fff'
      // }
    },
    legend: {
      data: ['确诊患者数', '治疗患者数'],
      bottom: 0,
      icon: 'rect',
      itemWidth: 2,
      itemHeight: 10,
      borderColor: '#e5e6eb',
      borderWidth: 2,
      padding: [6, 8, 6, 8]
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: true,
        // boundaryGap: ["10%", "40%"],
        axisLine: {
          onZero: false
        },
        data: treatmentAxias.value
        // axisLabel: {
        //   showMaxLabel: false,
        // },
      }
    ],
    yAxis: [
      {
        name: '',
        type: 'value'
      }
    ],
    dataZoom: [
      {
        show: true,
        height: 35,
        xAxisIndex: [0],
        bottom: 40,
        start: 0,
        end: 100,
        handleIcon:
          'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
        handleSize: '110%',
        handleStyle: {
          color: '#d3dee5'
        },
        textStyle: {
          color: '#fff'
        },
        borderColor: '#90979c'
      },
      {
        type: 'inside',
        show: true,
        height: 15
      }
    ],
    series: [
      {
        name: '确诊患者数',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(109, 210, 48, 0.8)'
            },
            {
              offset: 1,
              color: 'rgba(109, 210, 48, 0)'
            }
          ])
        },
        symbolSize: 0,
        data: treatmentConfirmData.value
      },
      {
        name: '治疗患者数',
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(56, 125, 255, 0.8)'
            },
            {
              offset: 1,
              color: 'rgba(56, 125, 255, 0)'
            }
          ])
        },
        symbolSize: 0,
        data: treatmentTreatNum.value
      }
    ]
  })
}

// 诊断检测
const initDiagnostic = () => {
  diagnosticData.value = []
  diagnosticDataRatio.value = []
  diagnostic({
    diseaseGroup: diseaseName
  }).then((res) => {
    isDiagnosticSpinning.value = false
    if (res.data) {
      diagnosticData.value = [['全部检测', '2015', '2016']]
      diagnosticData.value.push(
        ['胃镜', res.data.all.gcyNum],
        ['C14呼气试验', '', res.data.nonAll.c14Num],
        ['C13呼气试验', '', res.data.nonAll.c13Num],
        ['粪便抗原检测', '', res.data.nonAll.hpsaNum],
        ['非侵入性人次', res.data.all.nonInvasiveNum]
      )
      diagnosticDataRatio.value.push(
        '',
        res.data.all.gcyNumRatio,
        res.data.nonAll.c14NumRatio,
        res.data.nonAll.c13NumRatio,
        res.data.nonAll.hpsaNumRatio,
        res.data.all.nonInvasiveRatio
      )
      nonInvasiveRatio.value = res.data.all.nonInvasiveRatio
    }

    if (diagnosticDataRatio.value.length > 0) {
      nextTick(() => {
        initDiagnosticChart()
      })
    }
  })
}

const initDiagnosticChart = () => {
  const dom = document.getElementById('diagnostic-testing')
  let myChart = mainChart.getInstanceByDom(dom)
  if (!myChart) {
    myChart = mainChart.init(dom)
    chartsList.push(myChart)
  }

  myChart.setOption({
    title: {
      show: diagnosticDataRatio.value.length ? false : true,
      text: '暂无数据',
      left: 'center',
      top: 'middle',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    tooltip: {},
    dataset: {
      source: diagnosticData.value
    },
    legend: {
      top: 'center',
      right: 5,
      orient: 'vertical',
      itemHeight: 10,
      itemWidth: 10,
      itemGap: 20,
      formatter: (name) => {
        let val = ''
        let num = ''
        let percent = ''
        diagnosticData.value.forEach((element, index) => {
          if (element[0] === name) {
            val = element[0]
            num = element[1] ? element[1] : element[2]
            percent = diagnosticDataRatio.value[index]
          }
        })
        return `{title|${val}} ${percent}%  ${num}人次`
      },
      textStyle: {
        rich: {
          title: {
            width: 80
          }
        }
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['15%', '50%'],
        label: {
          position: 'center',
          formatter: '全部检测',
          textStyle: {
            fontSize: 16,
            fontWeight: 600
          }
        },
        startAngle: 45, // 起始角度 45
        clockwise: false, // 逆时针
        markLine: {
          lineStyle: {
            type: 'solid',
            color: '#BFBFBF'
          },
          silent: true,
          symbol: 'none',
          data: nonInvasiveRatio.value ? getMarkLineData(nonInvasiveRatio.value, myChart) : []
        }
      },
      {
        type: 'pie',
        radius: ['30%', '50%'],
        center: ['45%', '45%'],
        encode: {
          itemName: '全部检测',
          value: '2016'
        },
        label: {
          position: 'center',
          formatter: '非侵入性',
          textStyle: {
            fontSize: 14,
            fontWeight: 600
          }
        }
      }
    ]
  })
}

const getMarkLineData = (percent, myChart) => {
  // 1.获取画布 width,height
  let height = myChart.getHeight()
  let width = myChart.getWidth()

  // 2.  根据 series[0].center 获取圆心坐标
  let x0 = width * 0.17 // 圆心x轴坐标

  //3.圆边上点坐标
  // let x1   =   x0   +   r   *   cos(ao   *   3.14   /180   )
  // let y1   =   y0   +   r   *   sin(ao   *   3.14   /180   )

  // “非侵入性” 终点坐标series[0].startAngle 45
  let x1 = x0 + (height / 4) * Math.cos((45 * 3.14) / 180)
  let y1 = height * 0.4 - (height / 4) * Math.sin((45 * 3.14) / 180)

  let ao = 360 * (percent / 100) // 扇形角度

  let ao1 = 0 // 用来计算的坐标角度
  ao1 = ao <= 45 ? 45 - ao : 360 - (ao - 45)
  if (ao1 < 270 && ao1 > 45) ao1 = 270 // 角度当270用，要不样式不好看

  let x2 = 0,
    y2 = 0
  x2 = x0 + (height / 4) * Math.cos((ao1 * 3.14) / 180)
  y2 = height * 0.62 - (height / 4) * Math.sin((ao1 * 3.14) / 180)

  return [
    [
      { x: x1, y: y1 },
      { x: '45%', y: '20%' }
    ],
    [
      { x: x2, y: y2 },
      { x: '45%', y: '70%' }
    ]
  ]
}

const initChart = () => {
  initManage()
  initAi()
  initTreatment()
  initDiagnostic()
  initDrugPlan()
  initDrugSen()
}

const tabsChange = (value) => {
  activeKey.value = value + ''
  diseaseName = diseaseLite.value.filter((item) => item.id == value)[0].groupName

  isBasicSpinning.value = true
  isTreatmentSpinning.value = true
  isDiagnosticSpinning.value = true
  isResistentSpinning.value = true
  isAntibioticSpinning.value = true
  isDrugPlanSpinning.value = true
  isDetectionSpinning.value = true
  isDrugRenSpinning.value = true
  isManageSpinning.value = true

  init()
}

// 用药方案
const initDrugPlan = () => {
  drugPlanData.value = []
  drugPlan({ diseaseGroup: diseaseName }).then((res) => {
    isDrugPlanSpinning.value = false
    if (res.data && res.data.length) {
      res.data.forEach((element) => {
        drugPlanData.value.push({
          name: element.planName,
          value: element.useNum,
          ratio: element.useNumRatio
        })
      })
    }

    if (drugPlanData.value.length > 0) {
      nextTick(() => {
        therapeuticRegimen()
      })
    }
  })
}

// 用药方案
const therapeuticRegimen = () => {
  const dom = document.getElementById('therapeutic-regimen')
  let myChart = mainChart.getInstanceByDom(dom)
  if (!myChart) {
    myChart = mainChart.init(dom)
    chartsList.push(myChart)
  }
  myChart.setOption({
    title: {
      show: drugPlanData.value.length ? false : true,
      text: '暂无数据',
      left: 'center',
      top: 'middle',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    color: ['#608BFE', '#144FC5', '#FCD367', '#FF922E', '#33CEF0'],
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      top: 'center',
      right: 10,
      itemHeight: 10,
      itemWidth: 10,
      itemGap: 20,
      formatter: (name) => {
        let val = ''
        let num = ''
        let percent = ''
        drugPlanData.value.forEach((element, index) => {
          if (element.name === name) {
            val = element.name
            num = element.value
            percent = drugPlanData.value[index].ratio
          }
        })
        return `{title|${val}} {percent|${percent}%} ${num}人次`
      },
      textStyle: {
        rich: {
          title: {
            width: 70
          },
          percent: {
            width: 45
          }
        }
      }
    },
    series: [
      {
        type: 'pie',
        radius: '80%',
        center: ['30%', '50%'],
        labelLine: {
          show: false
        },
        label: {
          show: false
        },
        data: drugPlanData.value
      }
    ]
  })
}

// 耐药情况
const initDrugSen = () => {
  drupAxisData.value = []
  drupSeriesData.value = []
  resistantDrug({ diseaseGroup: diseaseName, zone: areaValue.value }).then((res) => {
    isDrugRenSpinning.value = false
    if (res.data) {
      res.data.forEach((element) => {
        drupAxisData.value.push(element.drugName)
        drupSeriesData.value.push(element.sensitivity)
      })
    }
    if (drupAxisData.value.length > 0) {
      nextTick(() => {
        drupResistance()
      })
    }
  })
}

const drupResistance = () => {
  const dom = document.getElementById('drug-resistance-situation')
  let myChart = mainChart.getInstanceByDom(dom)
  if (!myChart) {
    myChart = mainChart.init(dom)
    chartsList.push(myChart)
  }

  myChart.setOption({
    title: {
      show: drupAxisData.value.length ? false : true,
      text: '暂无数据',
      left: 'center',
      top: 'middle',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    color: ['#608BFE', '#4CD263', '#F9CC45', '#FCE996', '#A871E3'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    grid: {
      top: 40,
      left: 40,
      right: 2,
      bottom: 20
    },
    xAxis: [
      {
        type: 'category',
        data: drupAxisData.value,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '单位：%'
      }
    ],
    series: [
      {
        type: 'bar',
        barWidth: '24',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: '#6f97ff'
            },
            {
              offset: 1,
              color: '#4677fa'
            }
          ])
        },
        data: drupSeriesData.value
      }
    ]
  })
}

const handleAreaChange = (value) => {
  areaValue.value = value.target.value
  isDrugRenSpinning.value = true
  initDrugSen()
}

// 管理业务
const initManage = () => {
  manageAxisData.value = []
  autoAxisData.value = []
  healthAxisData.value = []
  aiAxisData.value = []
  manualAxisData.value = []
  adverseAxisData.value = []
  manage({
    id: activeKey.value,
    // diseaseGroup: diseaseName,
    startDate: businessTime.value.length
      ? dayjs(businessTime.value[0]).startOf('months').format('YYYY-MM-DD 00:00:00')
      : '',
    endDate: businessTime.value.length
      ? dayjs(businessTime.value[1]).endOf('months').format('YYYY-MM-DD 23:59:59')
      : ''
  }).then((res) => {
    isManageSpinning.value = false
    if (res.data) {
      res.data.forEach((element) => {
        manageAxisData.value.push(element.countDate)
        autoAxisData.value.push(element.remindNum)
        healthAxisData.value.push(element.educationNum)
        aiAxisData.value.push(element.aiFollowNum)
        manualAxisData.value.push(element.personFollowNum)
        adverseAxisData.value.push(element.adverseNum)
      })
      if (manageAxisData.value.length > 0) {
        nextTick(() => {
          manageBusiness()
        })
      }
    }
  })
}

const manageBusiness = () => {
  const dom = document.getElementById('manage-business')
  let myChart = mainChart.getInstanceByDom(dom)
  if (!myChart) {
    myChart = mainChart.init(dom)
    chartsList.push(myChart)
  }

  myChart.setOption({
    title: {
      show: manageAxisData.value.length ? false : true,
      text: '暂无数据',
      left: 'center',
      top: 'middle',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    color: ['#608BFE', '#4CD263', '#F9CC45', '#FCE996', '#A871E3'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    grid: {
      top: 40,
      left: 30,
      right: 2,
      bottom: 50
    },
    legend: {
      // data: ['智能提醒', '健康宣教', 'AI随访', '人工随访', '不良事件'],
      itemHeight: 10,
      itemWidth: 10,
      bottom: 0
    },
    xAxis: [
      {
        type: 'category',
        data: manageAxisData.value,
        axisPointer: {
          type: 'shadow'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '单位：人次'
      }
    ],
    series: [
      {
        name: '智能提醒',
        type: 'bar',
        // barWidth: 20,
        data: autoAxisData.value
      },
      {
        name: '健康宣教',
        type: 'bar',
        // barWidth: 20,
        data: healthAxisData.value
      },
      {
        name: 'AI随访',
        type: 'bar',
        stack: 'total',
        // barWidth: 20,
        data: aiAxisData.value
      },
      {
        name: '人工随访',
        type: 'bar',
        stack: 'total',
        // barWidth: 20,
        data: manualAxisData.value
      },
      {
        name: '不良事件',
        type: 'bar',
        // barWidth: 20,
        data: adverseAxisData.value
      }
    ]
  })
}

const businessTimeChange = (date, dateString) => {
  if (dateString[0]) {
    businessTime.value = [dayjs(dateString[0]), dayjs(dateString[1])]
  } else {
    businessTime.value = []
  }

  initManage()
}

// ai挖掘潜在患者数量
const initAi = () => {
  aiMiningData.value = []
  aiData({
    diseaseGroup: diseaseName
  }).then((res) => {
    if (res.data) {
      aiMiningData.value.push(
        {
          value: res.data.aiNum || 0,
          name: '筛选出患者'
        },
        {
          value: res.data.remindNum || 0,
          name: '智能提醒患者'
        },
        {
          name: '来院检查患者',
          value: res.data.visitNum || 0
        },
        {
          name: '确诊患者',
          value: res.data.confirmNum || 0
        }
      )
      if (aiMiningData.value.length > 0) {
        nextTick(() => {
          AIPotentialPatients()
        })
      }
    }
  })
}

const AIPotentialPatients = () => {
  const dom = document.getElementById('potential-number-patients')
  let myChart = mainChart.getInstanceByDom(dom)
  if (!myChart) {
    myChart = mainChart.init(dom)
    chartsList.push(myChart)
  }
  myChart.setOption({
    title: {
      show: aiMiningData.value.length ? false : true,
      text: '暂无数据',
      left: 'center',
      top: 'middle',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    backgroundColor: '#ffffff',
    color: ['#144FC5', '#4690F7', '#60A8F8', '#81BFF9'],
    tooltip: {
      trigger: 'item',
      formatter: '{b} : {c}'
    },
    legend: {
      top: 'center',
      left: '7%',
      orient: 'vertical',
      // data: ['筛选出患者', '智能提醒患者', '来院检查患者', '确诊患者'],
      itemHeight: 10,
      itemWidth: 10,
      itemGap: 40
    },

    // calculable: true,
    series: [
      {
        name: '漏斗图',
        type: 'funnel',
        minSize: '10',
        left: '30%',
        width: '60%',
        top: 0,
        gap: 2,
        bottom: 0,
        label: {
          show: true,
          position: 'inside',
          color: '#fff',
          formatter: '{c}'
        },
        emphasis: {
          textStyle: {
            fontSize: 20
          }
        },
        labelLine: {
          length: 10,
          lineStyle: {
            width: 1,
            type: 'solid'
          }
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 0
        },
        sort: 'none',
        data: aiMiningData.value
      }
    ]
  })
}
</script>
<style lang="less" scoped>
.box-main {
  width: 100%;
  height: 100%;
  padding: 0 !important;
  overflow: hidden !important;

  //   .topHeaderCard {
  //     background: #fff;
  //   }
  .bax-main-content {
    width: 100%;
    height: calc(100% - 50px);
    overflow: hidden auto;
  }

  .box-content {
    margin: 16px;
  }

  .title-name {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 600;
    color: #1d2129;
    box-shadow: -4px 0 0 -1px rgba(22, 93, 255, 1);
    padding-left: 12px;
    margin-bottom: 16px;
    display: inline-block;
  }

  .basic-info {
    width: 100%;
    height: 140px;
    margin: 16px 0;
    display: flex;

    .year-patient {
      flex: 1;
      margin-right: 8px;
      background: #f7f8fa;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: row;

      .icon-img {
        height: 100%;
        display: flex;
        align-items: center;
        margin-right: 10px;

        img {
          width: 48px;
          height: 48px;
        }
      }

      .info-content {
        margin-left: 10px;
        display: flex;
        align-items: flex-start;
        height: 100%;
        flex-direction: column;
        justify-content: center;
      }
    }

    .other-patient {
      flex: 5;
      margin-left: 8px;
      background: #f7f8fa;
      border-radius: 4px;
      display: flex;
      flex-direction: row;

      .first-patient,
      .first-treatment-num,
      .first-treatment-percent,
      .sec-treatment-num,
      .sec-treatment-percent {
        flex: 1;
        height: 100%;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
    }

    .data-col-title {
      font-size: 14px;
      font-weight: 400;
      color: #4e5969;
    }

    .data-yoy {
      font-size: 12px;
      font-weight: 400;
      color: #4e5969;
    }

    .data-value {
      font-size: 30px;
      color: #1d2129;

      span {
        font-family: D-DIN;
        font-weight: bold;
      }
    }
  }

  .content-title {
    background: #f7f8fa;
    padding-left: 16px;
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 600;
    color: #1d2129;
    line-height: 38px;
    margin-bottom: 16px;
  }

  #treatment-situation {
    width: 100%;
    height: 350px;
  }

  #diagnostic-testing {
    width: 100%;
    height: 220px;
  }

  #therapeutic-regimen {
    width: 100%;
    height: 200px;
  }

  .therapeutic-tips {
    display: flex;
    width: 100%;
    height: 70px;
    color: #4e5969;
  }

  #drug-resistance-situation {
    width: 100%;
    height: 270px;
  }

  #manage-business,
  #potential-number-patients {
    width: 100%;
    height: 300px;
  }
}

.ant-table-striped :deep(.table-striped) td {
  background-color: #f7f8fa;
}

.business-time-pick {
  position: absolute;
  right: 10px;
  top: 45px;
  z-index: 100;
}

.treatment-time-pick {
  position: absolute;
  right: 25px;
  top: 285px;
  z-index: 100;
}

.drug-area-pick {
  position: absolute;
  right: 10px;
  top: 45px;
  z-index: 100;
}
</style>

<style>
.bax-main-content .box-content .ant-empty-normal {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
</style>
